import type { AddressInfo } from 'net'

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number) {
  const map = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']

  let i = 0
  while (bytes > 1024 && i < map.length - 1) {
    bytes /= 1024
    i++
  }

  return `${bytes.toFixed(2).replace(/\.?0+$/, '')}${map[i]}B`
}

/**
 * 格式化用时
 */
export function formatDuration(ms: number) {
  if (ms < 1000) {
    return `${ms}ms`
  }

  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)

  const displaySeconds = seconds % 60
  const displayMinutes = minutes % 60
  const displayHours = hours

  let result = ''

  if (displayHours > 0) {
    result += `${displayHours}h `
  }
  if (displayMinutes > 0 || displayHours > 0) {
    result += `${displayMinutes}m `
  }
  if (displaySeconds > 0 || displayMinutes > 0 || displayHours > 0) {
    result += `${displaySeconds}s`
  }

  return result.trim()
}

export const formatAddressInfo = (info: Partial<AddressInfo>, defaultInfo: AddressInfo) => {
  for (const key in info) {
    if (!info[key as keyof AddressInfo]) {
      delete info[key as keyof AddressInfo]
    }
  }

  const address = info.address || ''

  if (address.startsWith('::ffff:')) {
    info.address = address.split(':').pop() || address
    info.family = 'IPv4'
  }

  return Object.assign({}, defaultInfo, info)
}
